package com.company.indicationshots.activity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.company.indicationshots.R;
import com.company.indicationshots.adapter.CommSettingSpinnerAdapter;
import com.company.indicationshots.database.DatabaseHelper;
import com.company.indicationshots.services.CommServices;
import com.company.indicationshots.util.BinaryToHexConverter;
import com.company.indicationshots.util.E22ParamMatch;
import com.company.indicationshots.util.EditLoseFocus;
import com.company.indicationshots.util.EditTextClick;
import com.company.indicationshots.util.HexToBinaryConverter;
import com.company.indicationshots.util.CommSpinnerClick;
import com.company.indicationshots.util.StringToTwoCharArray;
import com.target.communication.service.CommSer;
import com.target.communication.service.ICommData;
import com.target.communication.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

//通信设置页面
public class CommSettingActivity extends AppCompatActivity {
    //定义变量
    private final String TAG = "CommSettingActivity";
    String wirelessModule = "E22";
    String serialPort = "COM1";
    String baudRate = "9600bps";
    String checkout = "8N1";
    String airSpeed = "2.4Kbps";
    String baleLength = "240Bytes";
    String modulePower = "30dBm";
    String E22FreChan = "0";
    String dataRSSID = "禁用";
    String infoChanRSSI = "禁用";
    String transMode = "透传";
    String zjsn = "禁用";
    String LBTSn = "禁用";
    String WORRole = "接收方";
    String WORCycle = "2000ms";
    String networkID = "0";
    String secretKey = "0";
    String moduleAddress = "0";
    int index;
    List<String> baudRateData;
    CommSettingSpinnerAdapter baudRateAdapter;
    Spinner baudRateView;
    List<String> checkoutData;
    CommSettingSpinnerAdapter checkoutAdapter;
    Spinner checkoutView;
    List<String> airSpeedData;
    CommSettingSpinnerAdapter airSpeedAdapter;
    Spinner airSpeedView;
    List<String> baleLengthData;
    CommSettingSpinnerAdapter baleLengthAdapter;
    Spinner baleLengthView;
    List<String> WORRoleData;
    CommSettingSpinnerAdapter WORRoleAdapter;
    Spinner WORRoleView;
    List<String> WORCycleData;
    CommSettingSpinnerAdapter WORCycleAdapter;
    Spinner WORCycleView;
    List<String> modulePowerData;
    CommSettingSpinnerAdapter modulePowerAdapter;
    Spinner modulePowerView;
    List<String> transModeData;
    CommSettingSpinnerAdapter transModeAdapter;
    Spinner transModeView;
    List<String> zjsnData;
    CommSettingSpinnerAdapter zjsnAdapter;
    Spinner zjsnView;
    List<String> LBTSnData;
    CommSettingSpinnerAdapter LBTSnAdapter;
    Spinner LBTSnView;
    List<String> dataRSSIData;
    CommSettingSpinnerAdapter dataRSSIAdapter;
    Spinner dataRSSIView;
    List<String> infoChanRSSIData;
    CommSettingSpinnerAdapter infoChanRSSIAdapter;
    Spinner infoChanRSSIView;
    EditText moduleAddressView;
    EditText E22FreChanView;
    EditText networkIDView;
    EditText secretKeyView;
    public static final String writeParamsAction = "com.company.indicationshots.writeParamsAction";
    private CommSer commBinder;
    TextView paramText;
    boolean open;
    String sendData;
    String targetType;
    String serialPortPath;
    String createTime;


    //串口服务
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onBindingDied(ComponentName name) {
            ServiceConnection.super.onBindingDied(name);
        }

        //Activity与Service断开连接时回调该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "comm onServiceDisconnected");
        }

        //Activity与Service连接成功时回调该方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "comm onServiceConnected");
            commBinder = (CommSer) service;

            commBinder.setiDataSerial(new ICommData() {
                @Override
                public void dataCallBack(byte[] var1) {
                    //接收数据
                    String receiveData = StringUtil.bytesToHex(var1);
                    if ("C10009".equals(sendData)) {
                        //读取返回值处理
                        readParams(receiveData);
                    } else {
                        //写入返回值处理
                        writeParams(receiveData);
                    }
                }
            });
        }
    };

    @SuppressLint({"Range", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comm_setting);

        paramText = findViewById(R.id.paramText);
        TextView write = findViewById(R.id.write);
        TextView read = findViewById(R.id.read);

        TextView userSet = findViewById(R.id.userSet);
        TextView funcSet = findViewById(R.id.funcSet);

        userSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService();
                Intent intent = new Intent(CommSettingActivity.this, UserSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0); // 0表示没有动画
                finish();
            }
        });

        funcSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService();
                Intent intent = new Intent(CommSettingActivity.this, FuncSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0); // 0表示没有动画
                finish();
            }
        });

        ImageView commClose = findViewById(R.id.commClose);
        commClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService();
                Intent intent = new Intent(CommSettingActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

        // 设置下拉列表的样式，使用自定义布局
        Spinner wirelessModuleView = findViewById(R.id.wirelessModule);
        Spinner serialPortView = findViewById(R.id.serialPort);
        baudRateView = findViewById(R.id.baudRate);
        checkoutView = findViewById(R.id.checkout);
        airSpeedView = findViewById(R.id.airSpeed);
        baleLengthView = findViewById(R.id.baleLength);
        WORRoleView = findViewById(R.id.WORRole);
        WORCycleView = findViewById(R.id.WORCycle);
        modulePowerView = findViewById(R.id.modulePower);
        transModeView = findViewById(R.id.transMode);
        zjsnView = findViewById(R.id.zjsn);
        LBTSnView = findViewById(R.id.LBTSn);
        dataRSSIView = findViewById(R.id.dataRSSI);
        infoChanRSSIView = findViewById(R.id.infoChanRSSI);
        moduleAddressView = findViewById(R.id.moduleAddress);
        E22FreChanView = findViewById(R.id.E22_freChan);
        networkIDView = findViewById(R.id.networkID);
        secretKeyView = findViewById(R.id.secretKey);
        View checkoutLayout = findViewById(R.id.checkout_layout);
        View airSpeedLayout = findViewById(R.id.airSpeed_layout);
        View baleLengthLayout = findViewById(R.id.baleLength_layout);
        View secondLayout = findViewById(R.id.second_layout);
        View threeLayout = findViewById(R.id.three_layout);

        EditTextClick.setEditTextClickListener(moduleAddressView, this);
        EditTextClick.setEditTextClickListener(E22FreChanView, this);
        EditTextClick.setEditTextClickListener(networkIDView, this);
        EditTextClick.setEditTextClickListener(secretKeyView, this);

        List<String> wirelessModuleData = new ArrayList<String>() {{
            add("E22-400T30S");
            add("XBee PRO S3B");
        }};
        CommSettingSpinnerAdapter wirelessModuleAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, wirelessModuleData);
        wirelessModuleView.setAdapter(wirelessModuleAdapter);
        CommSpinnerClick.onClickSelectItem(wirelessModuleAdapter, wirelessModuleView);

        List<String> serialPortData = new ArrayList<String>() {{
            add("COM1");
            add("COM2");
            add("COM3");
            add("COM4");
        }};
        CommSettingSpinnerAdapter serialPortAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, serialPortData);
        serialPortView.setAdapter(serialPortAdapter);
        CommSpinnerClick.onClickSelectItem(serialPortAdapter, serialPortView);

        baudRateData = new ArrayList<String>() {{
            add("1200bps");
            add("2400bps");
            add("4800bps");
            add("9600bps");
            add("19200bps");
            add("38400bps");
            add("57600bps");
            add("115200bps");
        }};
        baudRateAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, baudRateData);
        baudRateView.setAdapter(baudRateAdapter);
        CommSpinnerClick.onClickSelectItem(baudRateAdapter, baudRateView);

        checkoutData = new ArrayList<String>() {{
            add("8N1");
            add("8O1");
            add("8E1");
        }};
        checkoutAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, checkoutData);
        checkoutView.setAdapter(checkoutAdapter);
        CommSpinnerClick.onClickSelectItem(checkoutAdapter, checkoutView);

        airSpeedData = new ArrayList<String>() {{
            add("2.4kbps");
            add("4.8kbps");
            add("9.6kbps");
            add("19.2kbps");
            add("38.4kbps");
            add("62.5kbps");
        }};
        airSpeedAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, airSpeedData);
        airSpeedView.setAdapter(airSpeedAdapter);
        CommSpinnerClick.onClickSelectItem(airSpeedAdapter, airSpeedView);

        baleLengthData = new ArrayList<String>() {{
            add("240bytes");
            add("128bytes");
            add("64bytes");
            add("32bytes");
        }};
        baleLengthAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, baleLengthData);
        baleLengthView.setAdapter(baleLengthAdapter);
        CommSpinnerClick.onClickSelectItem(baleLengthAdapter, baleLengthView);

        WORRoleData = new ArrayList<String>() {{
            add("接收方");
            add("发射方");
        }};
        WORRoleAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, WORRoleData);
        WORRoleView.setAdapter(WORRoleAdapter);
        CommSpinnerClick.onClickSelectItem(WORRoleAdapter, WORRoleView);

        WORCycleData = new ArrayList<String>() {{
            add("500ms");
            add("1000ms");
            add("1500ms");
            add("2000ms");
            add("2500ms");
            add("3000ms");
            add("3500ms");
            add("4000ms");
        }};
        WORCycleAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, WORCycleData);
        WORCycleView.setAdapter(WORCycleAdapter);
        CommSpinnerClick.onClickSelectItem(WORCycleAdapter, WORCycleView);

        modulePowerData = new ArrayList<String>() {{
            add("30dBm");
            add("27dBm");
            add("24dBm");
            add("21dBm");
        }};
        modulePowerAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, modulePowerData);
        modulePowerView.setAdapter(modulePowerAdapter);
        CommSpinnerClick.onClickSelectItem(modulePowerAdapter, modulePowerView);

        transModeData = new ArrayList<String>() {{
            add("透传");
            add("定传");
        }};
        transModeAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, transModeData);
        transModeView.setAdapter(transModeAdapter);
        CommSpinnerClick.onClickSelectItem(transModeAdapter, transModeView);

        zjsnData = new ArrayList<String>() {{
            add("禁用");
            add("启用");
        }};
        zjsnAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, zjsnData);
        zjsnView.setAdapter(zjsnAdapter);
        CommSpinnerClick.onClickSelectItem(zjsnAdapter, zjsnView);

        LBTSnData = new ArrayList<String>() {{
            add("禁用");
            add("启用");
        }};
        LBTSnAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, LBTSnData);
        LBTSnView.setAdapter(LBTSnAdapter);
        CommSpinnerClick.onClickSelectItem(LBTSnAdapter, LBTSnView);

        dataRSSIData = new ArrayList<String>() {{
            add("禁用");
            add("启用");
        }};
        dataRSSIAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, dataRSSIData);
        dataRSSIView.setAdapter(dataRSSIAdapter);
        CommSpinnerClick.onClickSelectItem(dataRSSIAdapter, dataRSSIView);

        infoChanRSSIData = new ArrayList<String>() {{
            add("禁用");
            add("启用");
        }};
        infoChanRSSIAdapter = new CommSettingSpinnerAdapter(this, R.layout.comm_spinner_item_layout, infoChanRSSIData);
        infoChanRSSIView.setAdapter(infoChanRSSIAdapter);
        CommSpinnerClick.onClickSelectItem(infoChanRSSIAdapter, infoChanRSSIView);

        loadUI();

        //绑定串口服务
        bindService();

        wirelessModuleView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                wirelessModuleAdapter.setSelectItem(position);
                if (position == 1) {
                    checkoutLayout.setVisibility(View.GONE);
                    airSpeedLayout.setVisibility(View.INVISIBLE);
                    baleLengthLayout.setVisibility(View.INVISIBLE);
                    secondLayout.setVisibility(View.INVISIBLE);
                    threeLayout.setVisibility(View.INVISIBLE);
                    baudRateData.add("230400bps");
                    baudRateAdapter.setSelectItem(3);
                    baudRateView.setSelection(3);
                    baudRateAdapter.notifyDataSetChanged();
                    read.setTextColor(Color.parseColor("#A9A9A9"));
                    read.setEnabled(false);
                    paramText.setText("待写入参数");
                } else {
                    checkoutLayout.setVisibility(View.VISIBLE);
                    airSpeedLayout.setVisibility(View.VISIBLE);
                    baleLengthLayout.setVisibility(View.VISIBLE);
                    secondLayout.setVisibility(View.VISIBLE);
                    threeLayout.setVisibility(View.VISIBLE);
                    baudRateData.remove("230400bps");
                    baudRateAdapter.setSelectItem(3);
                    baudRateView.setSelection(3);
                    baudRateAdapter.notifyDataSetChanged();
                    read.setTextColor(Color.WHITE);
                    read.setEnabled(true);
                    paramText.setText("待写入参数");
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //写入参数发送
        write.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                wirelessModule = wirelessModuleView.getSelectedItem().toString();
                serialPort = serialPortView.getSelectedItem().toString();
                createTime = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
                if ("E22-400T30S".equals(wirelessModule)) {
                    targetType = "光电靶";
                }
                if ("XBee PRO S3B".equals(wirelessModule)) {
                    targetType = "激波靶";
                }
                if ("".equals(wirelessModule)) {
                    targetType = "起倒靶";
                }
                if ("".equals(wirelessModule)) {
                    targetType = "影像靶";
                }

                if ("COM1".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS1";
                }
                if ("COM2".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS2";
                }
                if ("COM3".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS3";
                }
                if ("COM4".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS4";
                }

                baudRate = baudRateView.getSelectedItem().toString();

                if ("XBee PRO S3B".equals(wirelessModule)){
                    //发送数据
                    sendData = "C0XBee";
                    //调用写入后返回值处理方法
                    writeParams("C1XBee");
                    return;
                }

                //获取选择的参数值
                //波特率转二进制字符串
                String babit = E22ParamMatch.baudRateBit(baudRate);
                //校验转二进制字符串
                String checkout = checkoutView.getSelectedItem().toString();
                String chbit = E22ParamMatch.checkoutBit(checkout);
                //空中速率转二进制字符串
                String airSpeed = airSpeedView.getSelectedItem().toString();
                String airbit = E22ParamMatch.airSpeedBit(airSpeed);
                //以上三者相加转成十六进制字符串
                String spHex = BinaryToHexConverter.binaryToHex(babit + chbit + airbit).toUpperCase();

                //分包包长转二进制字符串
                String baleLength = baleLengthView.getSelectedItem().toString();
                String blbit = E22ParamMatch.baleLengthBit(baleLength);
                //模块功率转二进制字符串
                String modulePower = modulePowerView.getSelectedItem().toString();
                String mpbit = E22ParamMatch.modulePowerBit(modulePower);
                //以上两者相加转成十六进制字符串
                String hex7 = BinaryToHexConverter.binaryToHex(blbit + "0000" + mpbit).toUpperCase();

                //传输方式匹配整数值
                String transMode = transModeView.getSelectedItem().toString();
                String tmbit;
                if ("透传".equals(transMode)) {
                    tmbit = "0";
                } else {
                    tmbit = "1";//"定传"
                }
                //中继使能匹配整数值
                String zjsn = zjsnView.getSelectedItem().toString();
                String zjsnbit;
                if ("禁用".equals(zjsn)) {
                    zjsnbit = "0";
                } else {
                    zjsnbit = "1";
                }
                //LBT使能匹配整数值
                String LBTSn = LBTSnView.getSelectedItem().toString();
                String LBTSnbit;
                if ("禁用".equals(LBTSn)) {
                    LBTSnbit = "0";
                } else {
                    LBTSnbit = "1";
                }
                //WOR角色匹配整数值
                String WORRole = WORRoleView.getSelectedItem().toString();
                String WORRolebit;
                if ("接收方".equals(WORRole)) {
                    WORRolebit = "0";
                } else {
                    WORRolebit = "1";//"发射方"
                }
                //WOR周期匹配整数值
                String WORCycle = WORCycleView.getSelectedItem().toString();
                String WORCycleBit = E22ParamMatch.WORCycleBit(WORCycle);
                //以上五者转成十六进制字符串
                String hex9 = BinaryToHexConverter.binaryToHex("0" + tmbit + zjsnbit + LBTSnbit + WORRolebit + WORCycleBit).toUpperCase();

                //获取模块地址
                String moduleAddress = moduleAddressView.getText().toString();
                int maInt = 0;
                if (StrUtil.isNumeric(moduleAddress)) {
                    maInt = Integer.parseInt(moduleAddress);
                    if (maInt < 0 || maInt > 65535) {
                        paramText.setText("写入失败,设备没有响应");
                        return;
                    }
                } else {
                    paramText.setText("写入失败,设备没有响应");
                    return;
                }
                //模块地址取商为高位值
                int maIntHigh = maInt / 256;
                //模块地址取余为低位值
                int maIntLow = maInt % 256;
                //高位值转成十六进制字符串
                String maHexHigh = Integer.toHexString(maIntHigh).toUpperCase();
                maHexHigh = maHexHigh.length() == 1 ? "0" + maHexHigh : maHexHigh;
                //低位值转成十六进制字符串
                String maHexLow = Integer.toHexString(maIntLow).toUpperCase();
                maHexLow = maHexLow.length() == 1 ? "0" + maHexLow : maHexLow;
                //以上两者拼接
                String maHex = maHexHigh + maHexLow;
                //获取频率信道
                String freChanText = E22FreChanView.getText().toString();
                Integer freChan = null;
                if (StrUtil.isNumeric(freChanText)) {
                    freChan = Integer.parseInt(freChanText);
                    if (freChan < 0 || freChan > 80) {
                        paramText.setText("写入失败,设备没有响应");
                        return;
                    }
                } else {
                    paramText.setText("写入失败,设备没有响应");
                    return;
                }
                //频率信道转成十六进制字符串
                String freChanHex = Integer.toHexString(freChan).toUpperCase();
                freChanHex = freChanHex.length() == 1 ? "0" + freChanHex : freChanHex;

                //获取网络ID
                String networkID = networkIDView.getText().toString();
                int niInt = 0;
                if (StrUtil.isNumeric(networkID)) {
                    niInt = Integer.parseInt(networkID);
                    if (niInt < 0 || niInt > 255) {
                        paramText.setText("写入失败,设备没有响应");
                        return;
                    }
                } else {
                    paramText.setText("写入失败,设备没有响应");
                    return;
                }
                //网络ID转成十六进制字符串
                String niHex = Integer.toHexString(niInt).toUpperCase();
                niHex = niHex.length() == 1 ? "0" + niHex : niHex;

                //获取密钥
                String secretKey = secretKeyView.getText().toString();
                int skInt = 0;
                if (StrUtil.isNumeric(secretKey)) {
                    skInt = Integer.parseInt(secretKey);
                    if (skInt < 0 || skInt > 65535) {
                        paramText.setText("写入失败,设备没有响应");
                        return;
                    }
                } else {
                    paramText.setText("写入失败,设备没有响应");
                    return;
                }

                //密钥取商为高位值
                int skIntHigh = skInt / 256;
                //密钥取余为低位值
                int skIntLow = skInt % 256;
                //高位值转成十六进制字符串
                String skHexHigh = Integer.toHexString(skIntHigh).toUpperCase();
                skHexHigh = skHexHigh.length() == 1 ? "0" + skHexHigh : skHexHigh;
                //低位值转成十六进制字符串
                String skHexLow = Integer.toHexString(skIntLow).toUpperCase();
                skHexLow = skHexLow.length() == 1 ? "0" + skHexLow : skHexLow;
                //以上两者拼接
                String skHex = skHexHigh + skHexLow;

                //把以上所有获取的转成十六进制的参数拼接成整个发送数据字符串
                sendData = "C00009" + maHex + niHex + spHex + hex7 + freChanHex + hex9 + skHex;

                try {
                    commBinder.setSerialPortPath(serialPortPath);
                    commBinder.setBaudRate(9600);
                    openSerial();
                    commBinder.send(sendData);
                    Thread.sleep(1000);

                } catch (IOException | InterruptedException e) {
                    paramText.setText("写入失败,设备没有响应");
                    throw new RuntimeException(e);
                }

                //使EditText失去焦点
                moduleAddressView.clearFocus();
                E22FreChanView.clearFocus();
                networkIDView.clearFocus();
                secretKeyView.clearFocus();
                // 获取InputMethodManager实例
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 关闭软键盘
                imm.hideSoftInputFromWindow(E22FreChanView.getWindowToken(), 0);

            }
        });

        //读取参数
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String wirelessModule = wirelessModuleView.getSelectedItem().toString();
                String serialPort = serialPortView.getSelectedItem().toString();
                String serialPortPath = null;
                if ("COM1".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS1";
                }
                if ("COM2".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS2";
                }
                if ("COM3".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS3";
                }
                if ("COM4".equals(serialPort)) {
                    serialPortPath = "/dev/ttyS4";
                }

                //读取发送数据
                sendData = "C10009";

                try {
                    commBinder.setSerialPortPath(serialPortPath);
                    commBinder.setBaudRate(9600);
                    openSerial();
                    commBinder.send(sendData);
                    Thread.sleep(1000);

                } catch (IOException | InterruptedException e) {
                    paramText.setText("读取失败,设备没有响应");
                    e.printStackTrace();
                }

            }
        });

        ConstraintLayout layout = findViewById(R.id.commSetLayout);

        EditLoseFocus.loseFocus(layout, this, moduleAddressView);
        EditLoseFocus.loseFocus(layout, this, E22FreChanView);
        EditLoseFocus.loseFocus(layout, this, networkIDView);
        EditLoseFocus.loseFocus(layout, this, secretKeyView);

    }

    //读取参数接收返回值后处理方法
    private void readParams(String receiveData) {

        //校验读取发送数据和读取接收数据
        if (StrUtil.isNotBlank(receiveData) && receiveData.startsWith(sendData)) {
            //读取接收数据生成一个十六进制字符串数组，每两位为一项
            String[] rtHexArray = StringToTwoCharArray.transform(receiveData);
            //数组元素转成二进制字符串
            String bit1 = HexToBinaryConverter.hexToBinary(rtHexArray[6]);
            //截取二进制字符串，转成对应波特率
            String baBit = bit1.substring(0, 3);
            baudRate = E22ParamMatch.baudRateValue(baBit);
            //截取二进制字符串，转成对应校验
            String chBit = bit1.substring(3, 5);
            checkout = E22ParamMatch.checkoutValue(chBit);
            //截取二进制字符串，转成对应空中速率
            String aiBit = bit1.substring(5);
            airSpeed = E22ParamMatch.airSpeedValue(aiBit);
            //数组元素转成二进制字符串
            String bit2 = HexToBinaryConverter.hexToBinary(rtHexArray[7]);
            //截取二进制字符串，转成对应分包包长
            String blBit = bit2.substring(0, 2);
            baleLength = E22ParamMatch.baleLengthValue(blBit);
            //截取二进制字符串，转成对应模块功率
            String mpBit = bit2.substring(6);
            modulePower = E22ParamMatch.modulePowerValue(mpBit);

            //数组元素转成十进制频率信道
            E22FreChan = Integer.parseInt(rtHexArray[8], 16) + "";

            String bit3 = HexToBinaryConverter.hexToBinary(rtHexArray[9]);
            //截取字符串生成对应的数据RSSI和信道RSSI
            String drBit = bit3.substring(0, 1);
            if ("0".equals(drBit)) {
                dataRSSID = "禁用";
                infoChanRSSI = "禁用";
            } else {
                dataRSSID = "启用";
                infoChanRSSI = "启用";
            }
            //截取字符串生成对应的传输方式
            String tmBit = bit3.substring(1, 2);
            if ("0".equals(tmBit)) {
                transMode = "透传";
            } else {
                transMode = "定传";
            }
            //截取字符串生成对应的中继使能
            String zjsnBit = bit3.substring(2, 3);
            if ("0".equals(zjsnBit)) {
                zjsn = "禁用";
            } else {
                zjsn = "启用";
            }
            //截取字符串生成对应的LBT使能
            String LBTSnBit = bit3.substring(3, 4);
            if ("0".equals(LBTSnBit)) {
                LBTSn = "禁用";
            } else {
                LBTSn = "启用";
            }
            //截取字符串生成对应的WOR角色
            String WORRoleBit = bit3.substring(4, 5);
            if ("0".equals(WORRoleBit)) {
                WORRole = "接收方";
            } else {
                WORRole = "发射方";
            }
            //截取字符串生成对应的WOR周期
            String WORCycleBit = bit3.substring(5);
            WORCycle = E22ParamMatch.WORCycleValue(WORCycleBit);

            //数组元素转成对应的十进制网络ID
            networkID = Integer.parseInt(rtHexArray[5], 16) + "";

            //数组元素转成对应的十进制模块地址
            //高位
            int mahigh = Integer.parseInt(rtHexArray[3], 16);
            //低位
            int malow = Integer.parseInt(rtHexArray[4], 16);
            //计算出对应的十进制频率信道
            moduleAddress = mahigh * 256 + malow + "";

            updateUI(paramText, "读取成功\n参数:" + receiveData);

        } else {
            updateUI(paramText, "读取失败,设备没有响应");
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadUI();
            }
        });

    }

    //写入参数接收返回值后处理方法
    private void writeParams(String receiveData) {

        //把模块写入发送数据的前两个字符替换成C1
        StringBuilder wssb = new StringBuilder(sendData);
        String rpws = String.valueOf(wssb.replace(0, 2, "C1"));

        DatabaseHelper dbHelper = new DatabaseHelper(CommSettingActivity.this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        //模块写入接收的数据和发送的数据进行校验
        if (StrUtil.isNotBlank(receiveData) && rpws.equals(receiveData)) {
            //部分写入数据存库
            //开始事务
            db.beginTransaction();
            try {
                String sql = "delete from commset";
                db.execSQL(sql);

                //波特率获取整数部分
                Integer br = Integer.parseInt(baudRate.substring(0, baudRate.indexOf("b")));
                ContentValues values = new ContentValues();
                values.put("targetType", targetType);
                values.put("wirelessModule", wirelessModule);
                values.put("serialPort", serialPort);
                values.put("serialPortPath", serialPortPath);
                values.put("baudRate", br);
                values.put("createTime", createTime);
                db.insert("commset", null, values);

                db.setTransactionSuccessful();

                if ("E22-400T30S".equals(wirelessModule)){
                    updateUI(paramText, "写入成功\n参数:" + sendData);
                }
                else if("XBee PRO S3B".equals(wirelessModule)) {
                    updateUI(paramText, "写入成功");
                }


                //广播发送
                Intent intent = new Intent(writeParamsAction);
                //可以添加额外的数据到Intent中，添加串口路径和波特率
                intent.putExtra("serialPortPath", serialPortPath);
                intent.putExtra("baudRate", br);
                LocalBroadcastManager.getInstance(CommSettingActivity.this).sendBroadcast(intent);

            } catch (SQLException e) {
                updateUI(paramText, "写入失败,设备没有响应");
                e.printStackTrace();
            } finally {
                db.endTransaction();
                db.close();
            }
        } else {
            updateUI(paramText, "写入失败,设备没有响应");
        }
    }

    public void loadUI() {
        index = baudRateData.indexOf(baudRate);
        baudRateAdapter.setSelectItem(index);
        baudRateView.setSelection(index);

        index = checkoutData.indexOf(checkout);
        checkoutAdapter.setSelectItem(index);
        checkoutView.setSelection(index);

        index = airSpeedData.indexOf(airSpeed);
        airSpeedAdapter.setSelectItem(index);
        airSpeedView.setSelection(index);

        index = baleLengthData.indexOf(baleLength);
        baleLengthAdapter.setSelectItem(index);
        baleLengthView.setSelection(index);

        index = WORRoleData.indexOf(WORRole);
        WORRoleAdapter.setSelectItem(index);
        WORRoleView.setSelection(index);

        index = WORCycleData.indexOf(WORCycle);
        WORCycleAdapter.setSelectItem(index);
        WORCycleView.setSelection(index);

        index = modulePowerData.indexOf(modulePower);
        modulePowerAdapter.setSelectItem(index);
        modulePowerView.setSelection(index);

        index = transModeData.indexOf(transMode);
        transModeAdapter.setSelectItem(index);
        transModeView.setSelection(index);

        index = zjsnData.indexOf(zjsn);
        zjsnAdapter.setSelectItem(index);
        zjsnView.setSelection(index);

        index = LBTSnData.indexOf(LBTSn);
        LBTSnAdapter.setSelectItem(index);
        LBTSnView.setSelection(index);

        index = dataRSSIData.indexOf(dataRSSID);
        dataRSSIAdapter.setSelectItem(index);
        dataRSSIView.setSelection(index);

        index = infoChanRSSIData.indexOf(infoChanRSSI);
        infoChanRSSIAdapter.setSelectItem(index);
        infoChanRSSIView.setSelection(index);

        moduleAddressView.setText(moduleAddress);
        E22FreChanView.setText(E22FreChan);
        networkIDView.setText(networkID);
        secretKeyView.setText(secretKey);
    }

    private void updateUI(TextView view, String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.setText(text);
            }
        });
    }

    //串口服务w
    /*
     *   绑定服务
     * */
    private void bindService() {
        Intent intent = new Intent(this, CommServices.class);
        intent.putExtra("param", "param1");
        Log.i(TAG, "comm bindService");
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }

    //解绑服务
    private void unbindService() {
        if (commBinder == null) {
            Log.i(TAG, "comm unbindService,binder is null");
            return;
        }
        unbindService(conn);
        commBinder = null;
        Log.i("comm unbindService", "comm unbindService success");
    }

    //打开串口
    public void openSerial() throws IOException {
        open = commBinder.connSerial();
        Log.i("comm openSerial", "comm serial open success");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
